package com.atguigu.tingshu.payment.service.impl;

import com.atguigu.tingshu.account.client.RechargeInfoFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.order.client.OrderInfoFeignClient;
import com.atguigu.tingshu.payment.config.WxPayV3Config;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.atguigu.tingshu.payment.service.WxPayService;
import com.atguigu.tingshu.payment.util.PayUtil;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.exception.ServiceException;
import com.wechat.pay.java.core.exception.ValidationException;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.*;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.refund.RefundService;
import com.wechat.pay.java.service.refund.model.AmountReq;
import com.wechat.pay.java.service.refund.model.CreateRequest;
import com.wechat.pay.java.service.refund.model.Refund;
import com.wechat.pay.java.service.refund.model.Status;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WxPayServiceImpl implements WxPayService {

    @Autowired
    private PaymentInfoService paymentInfoService;
    @Resource
    private OrderInfoFeignClient orderInfoFeignClient;
    @Resource
    private UserInfoFeignClient userInfoFeignClient;
    @Resource
    private RechargeInfoFeignClient rechargeInfoFeignClient;
    @Resource
    private RSAAutoCertificateConfig config;
    @Resource
    private WxPayV3Config wxPayV3Config;

    @Override
    public Map<String, Object> createJsapi(Long userId, String orderNo, String paymentType) {
        //  将数据惊进行封装 放到Map里面 5个key  保存交易记录
        Map<String, Object> result = new HashMap<>();
        //  声明一个充值变量
        BigDecimal totalAmount = new BigDecimal("0.00");
        // 判断微信支付的用途 是用于微信支付  还是微信充值
        Result<OrderInfo> orderInfoResult = this.orderInfoFeignClient.getOrderInfo(orderNo);
        Assert.notNull(orderInfoResult, "远程调用获取订单信息失败");
        OrderInfo orderInfo = orderInfoResult.getData();
        if (paymentType.equals(SystemConstant.PAYMENT_TYPE_ORDER)) {
            // 微信支付
            if (null != orderInfo || !SystemConstant.ORDER_STATUS_UNPAID.equals(orderInfo.getOrderStatus())) {
                //  抛异常
                throw new RuntimeException("订单不存在");
            }
            totalAmount = orderInfo.getOrderAmount();
        } else {
            // 微信充值
            Result<RechargeInfo> rechargeInfoResult = rechargeInfoFeignClient.getRechargeInfo(orderNo);
            Assert.notNull(rechargeInfoResult, "远程调用获取充值信息失败");
            RechargeInfo rechargeInfo = rechargeInfoResult.getData();
            Assert.notNull(rechargeInfo, "远程调用获取充值信息失败");
            //	获取金额；
            totalAmount = rechargeInfo.getRechargeAmount();
        }

        //  保存交易记录
        paymentInfoService.savePaymentInfo(userId, orderNo, paymentType, totalAmount);

        // 使用 微信支付公钥的RSA配置
        JsapiServiceExtension service = new JsapiServiceExtension.Builder().config(config).build();
        // 跟之前的下单示例一样 填充预下单参数
        PrepayRequest request = new PrepayRequest();
        Amount amount = new Amount();
        amount.setTotal(orderInfo.getOrderAmount().intValue());
        request.setAmount(amount);
        request.setAppid(wxPayV3Config.getAppid());
        request.setMchid(wxPayV3Config.getMerchantId());
        request.setDescription("测试商品标题");
        request.setNotifyUrl(wxPayV3Config.getNotifyUrl());
        // orderNo:叫做商户订单号！
        request.setOutTradeNo(orderNo);
        //设置支付者信息
        Payer payer = new Payer();
        // 获取用户信息
        Result<UserInfoVo> userInfoVoResult = userInfoFeignClient.getUserInfo(userId);
        Assert.notNull(userInfoVoResult, "远程调用获取用户信息失败");
        UserInfoVo userInfoVo = userInfoVoResult.getData();
        Assert.notNull(userInfoVo, "远程调用获取用户信息失败");
        payer.setOpenid(userInfoVo.getWxOpenId());
        request.setPayer(payer);
        //	request.setTimeExpire();
        // response包含了调起支付所需的所有参数，可直接用于前端调起支付
        PrepayWithRequestPaymentResponse response = service.prepayWithRequestPayment(request);
        //	封装结果;
        result.put("timeStamp", response.getTimeStamp()); // 时间戳
        result.put("nonceStr", response.getNonceStr());   // 随机字符串
        result.put("package", response.getPackageVal());  // 订单详情扩展字符串
        result.put("signType", response.getSignType());   // 签名方式
        result.put("paySign", response.getPaySign());     // 签名
        //	返回数据
        return result;
    }

    @Override
    public Transaction queryPayStatus(String orderNo) {
        // 构建service
        try {
            JsapiServiceExtension service = new JsapiServiceExtension.Builder().config(config).build();
            QueryOrderByOutTradeNoRequest queryOrderByOutTradeNoRequest = new QueryOrderByOutTradeNoRequest();
            queryOrderByOutTradeNoRequest.setMchid(wxPayV3Config.getMerchantId());
            queryOrderByOutTradeNoRequest.setOutTradeNo(orderNo);

            Transaction transaction = service.queryOrderByOutTradeNo(queryOrderByOutTradeNoRequest);

            return transaction;
        } catch (ServiceException e) {
            // API返回失败, 例如ORDER_NOT_EXISTS
            System.out.printf("code=[%s], message=[%s]\n", e.getErrorCode(), e.getErrorMessage());
            System.out.printf("reponse body=[%s]\n", e.getResponseBody());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Transaction wxNotify(HttpServletRequest request) {
        //	获取请求头中的数据;
        String wechatPaySerial = request.getHeader("Wechatpay-Serial");
        String wechatpayNonce = request.getHeader("Wechatpay-Nonce");
        String wechatTimestamp = request.getHeader("Wechatpay-Timestamp");
        String wechatSignature = request.getHeader("Wechatpay-Signature");
        //	请求体不能更改；
        String requestBody = PayUtil.readData(request);
        // 构造 RequestParam
        RequestParam requestParam = new RequestParam.Builder()
                .serialNumber(wechatPaySerial)
                .nonce(wechatpayNonce)
                .signature(wechatSignature)
                .timestamp(wechatTimestamp)
                .body(requestBody)
                .build();
        // 初始化 NotificationParser
        NotificationParser parser = new NotificationParser(config);
        try {
            // 以支付通知回调为例，验签、解密并转换成 Transaction
            Transaction transaction = parser.parse(requestParam, Transaction.class);
            //	返回数据;
            return transaction;
        } catch (ValidationException e) {
            // 签名验证失败，返回 401 UNAUTHORIZED 状态码
            log.error("sign verification failed", e);
        }
        //	返回空对象
        return null;
    }

    @Override
    public Map<String, Object> createNative(String paymentType, String orderNo, Long userId) {
        BigDecimal totalAmount = new BigDecimal("0.00");

        try {
            //保存支付记录
             paymentInfoService.savePaymentInfo(userId, orderNo, paymentType,totalAmount);

            // 构建service
            NativePayService service = new NativePayService.Builder().config(config).build();
            // request.setXxx(val)设置所需参数，具体参数可见Request定义
            com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest request = new com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest();
            com.wechat.pay.java.service.payments.nativepay.model.Amount amount = new com.wechat.pay.java.service.payments.nativepay.model.Amount();
            amount.setTotal(1);
            request.setAmount(amount);
            request.setAppid(wxPayV3Config.getAppid());
            request.setMchid(wxPayV3Config.getMerchantId());
            request.setDescription("测试商品标题");
            request.setNotifyUrl(wxPayV3Config.getNotifyUrl());
            request.setOutTradeNo(orderNo);

            // 调用下单方法，得到应答
            com.wechat.pay.java.service.payments.nativepay.model.PrepayResponse response = service.prepay(request);
            // 使用微信扫描 code_url 对应的二维码，即可体验Native支付
            System.out.println(response.getCodeUrl());

            Map result = new HashMap<>();
            result.put("codeUrl", response.getCodeUrl());
            return result;
        } catch (ServiceException e) {
            e.printStackTrace();
            throw new GuiguException( 201, e.getErrorMessage());
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            throw new GuiguException( 201, "订单号不存在");
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuiguException( 201, "微信下单异常");
        }
    }

    @Override
    public boolean refund(String orderNo) {
        // 创建退款对象
        RefundService refundService = new RefundService.Builder().config(config).build();
        //  创建退款请求对象
        CreateRequest createRequest = new CreateRequest();
        createRequest.setOutTradeNo(orderNo);
        createRequest.setOutRefundNo(orderNo);
        AmountReq amountReq = new AmountReq();
        amountReq.setRefund(1l);
        amountReq.setTotal(1l);
        amountReq.setCurrency("CNY");
        createRequest.setAmount(amountReq);
        Refund refund = refundService.create(createRequest);
        //  判断
        if (refund.getStatus().equals(Status.SUCCESS)){
            //  关闭交易记录
            this.paymentInfoService.closePayment(orderNo);
            //  修改订单状态.
            return true;
        }
        return false;
    }
}
